package com.ruoyi.quartz.task;

import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Component;

import com.ruoyi.common.enums.TaskStatus;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.system.domain.Device;
import com.ruoyi.system.domain.Task;
import com.ruoyi.system.service.IDeviceService;
import com.ruoyi.system.service.ITaskService;

/**
 * 任务处理
 * 
 * @author yanghao
 */
@Component("taskTask")
public class TaskTask {

	private static final Logger log = LoggerFactory.getLogger(TaskTask.class);

	@Autowired
	private ITaskService taskService;

	private static ExecutorService executor = Executors.newSingleThreadExecutor();

	/*
	 * WAITING("0", "等待创建"), CREATING("1", "创建中"), FAILING("2", "创建失败"),
	 * SUCCESS("3", "创建成功"), ENDING("4", "任务结束");
	 */

	/**
	 * 处理等待任务
	 */
	public void taskWaitingDeal() {
		System.out.println("taskTask:开始处理等待任务");
		Task task = new Task();
		task.setState(TaskStatus.WAITING_CREATING.getCode());
		List<Task> tasklist = taskService.selectTaskList(task);
		for (Task tk : tasklist) {
			TaskWaitingCreatingHandlerCallable taskWaitingHandlerCallable = new TaskWaitingCreatingHandlerCallable(tk);
			Future<Map<String, String>> futureTask = executor.submit(taskWaitingHandlerCallable);
		}

	}

	/**
	 * 处理删除任务
	 */
	public void taskDeletingDeal() {
		System.out.println("taskTask:开始处理删除任务");
		Task task = new Task();
		task.setState(TaskStatus.WAITING_DELETING.getCode());
		List<Task> tasklist = taskService.selectTaskList(task);
		for (Task tk : tasklist) {
			TaskDeletingHandlerCallable taskWaitingHandlerCallable = new TaskDeletingHandlerCallable(tk);
			Future<Map<String, String>> futureTask = executor.submit(taskWaitingHandlerCallable);
		}

	}

	private static class TaskDeletingHandlerCallable implements Callable<Map<String, String>> {
		private Task task;

		public TaskDeletingHandlerCallable(Task task) {
			this.task = task;
		}

		static private ITaskService taskService = SpringUtils.getBean(ITaskService.class);;

		static private IDeviceService deviceService = SpringUtils.getBean(IDeviceService.class);;

		@Override
		public Map<String, String> call() {
			Map<String, String> dataMap = new LinkedHashMap<>();
			String notes = "";
			if (this.task != null) {
				// 修改任务状态
				this.task.setState(TaskStatus.DELETING.getCode());
				this.task.setGmtModify(new Date());
				this.taskService.updateTask(task);
				Device device = deviceService.selectDeviceByDeviceId(this.task.getDeviceId());
				if (device != null) {
					// 获取任务执行的设备信息
					// 调用启动容器命令
					String cmd = StringUtils.format(
							"sudo salt {} cmd.run '/usr/bin/sh /etc/salt/yanghaojy32/remove_docker.sh {} '",
							device.getDeviceName(), task.getDockerId());
					String cmdResult = SaltFn.execCommand(cmd);
					Object object = SaltFn.getKeyValue(cmdResult, StringUtils.format("{}", device.getDeviceName()));
					if (object != null) {
						String resultMsg = object.toString();
						if (!StringUtils.isEmpty(resultMsg)) {
							if (resultMsg.contains("success")) {
								// delete容器成功
								log.info("{} delete docker success", task.getTaskId());
								this.task.setGmtModify(new Date());
								this.task.setState(TaskStatus.ENDING.getCode());
								this.task.setNotes("删除容器成功成功");
								this.taskService.updateTask(task);
								return dataMap;
							}
							notes = resultMsg;
						}

					}
				} else {
					notes = "任务所在设备找不到";
				}
				this.task.setNotes(notes);
				this.task.setGmtModify(new Date());
				this.task.setState(TaskStatus.DELETING_FAILING.getCode());
				this.taskService.updateTask(task);
			}
			return dataMap;
		}

	}

	private static class TaskWaitingCreatingHandlerCallable implements Callable<Map<String, String>> {
		private Task task;

		public TaskWaitingCreatingHandlerCallable(Task task) {
			this.task = task;
		}

		static private ITaskService taskService = SpringUtils.getBean(ITaskService.class);;

		static private IDeviceService deviceService = SpringUtils.getBean(IDeviceService.class);;

		@Override
		public Map<String, String> call() {
			Map<String, String> dataMap = new LinkedHashMap<>();
			String notes = "";
			if (this.task != null) {
				// 修改任务状态
				this.task.setState(TaskStatus.CREATING.getCode());
				this.task.setGmtModify(new Date());
				this.taskService.updateTask(task);
				Device device = deviceService.selectDeviceByDeviceId(this.task.getDeviceId());
				if (device != null) {
					// 获取任务执行的设备信息
					// 调用启动容器命令
					// port信息：2222
					int port = 2222;
					String cmd = StringUtils.format(
							"sudo salt {} cmd.run '/usr/bin/sh /etc/salt/yanghaojy32/start_docker.sh {} {}'",
							device.getDeviceName(), port, task.getUserId());
					String cmdResult = SaltFn.execCommand(cmd);
					Object object = SaltFn.getKeyValue(cmdResult, StringUtils.format("{}", device.getDeviceName()));
					if (object != null) {
						String resultMsg = object.toString();
						if (!StringUtils.isEmpty(resultMsg)) {
							Map<String, String> map = SaltFn.getDockerInfo(resultMsg);
							if (map.containsKey("port") && map.containsKey("containerId")) {
								// 创建容器成功
								log.info("{} create docker success", device.getDeviceName());
								this.task.setDockerId(map.get("containerId"));
								this.task.setIp(device.getIp() + ":" + map.get("port"));
								this.task.setGmtModify(new Date());
								this.task.setState(TaskStatus.CREATING_SUCCESS.getCode());
								this.task.setNotes("创建成功");
								this.taskService.updateTask(task);
								return dataMap;
							}
							if (resultMsg.contains(SaltFn.DOCKER_ERROR_MESSAGE)) {
								log.error("{} create docker fail", device.getDeviceName());
							} else {
								log.error("{} create docker fail", device.getDeviceName());
							}
							notes = resultMsg;
						}

					}
				} else {
					notes = "任务所在设备找不到";
				}
				this.task.setNotes(notes);
				;
				this.task.setGmtModify(new Date());
				this.task.setState(TaskStatus.CREATING_FAILING.getCode());
				this.taskService.updateTask(task);
			}
			return dataMap;
		}

	}

	public static void main(String[] args) {
		int port = 2222;
		String cmd = StringUtils.format(
				"sudo salt {} cmd.run '/usr/bin/sh /etc/salt/yanghaojy32/start_docker.sh {} {}'", "ddm", port, "ddm");
		String cmdResult = SaltFn.execCommand(cmd);
		Object object = SaltFn.getKeyValue(cmdResult, StringUtils.format("{}", "ddm"));
		if (object != null) {
			String resultMsg = object.toString();
			if (!StringUtils.isEmpty(resultMsg) && resultMsg.contains(SaltFn.DOCKER_ERROR_MESSAGE)) {
				log.info("{} ip is blank ", "ddm");
			}
		}
	}

}
